var express = require('express');
var router = express.Router();

var Article = require('../models/article')
var Visit = require('../models/visit')

var util = require('../utility/util')

router.get('/', function (req, res) {

  var ip = util.getClientIp(req)

  Article.getAll(function (err, articles) {
    if (err) {
      console.log('home.js fail. err = ' + err)
      next()
    } else {
      Visit.getByIp(ip, function (err, visit) {
        if (err) {
          console.log('home.js fail. err = ' + err)
          next()
        } else {
          if (!visit) {
            Visit.create(ip, function (err, visit) {
              res.render('home', {
                title: '我的主页',
                list: articles,
                visit: visit
              })
            })
          } else {
            Visit.increaseCount(ip, function (err, visit) {
              res.render('home', {
                title: '我的主页',
                list: articles,
                visit: visit
              })
            })
          }
        }
      })
    }
  })
})


module.exports = router;
